/**
 * @author Kostya
 */
Ext.uniqueId = function(){
	var t = String(new Date().getTime()).substr(4);
	var s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	for(var i = 0; i < 4; i++){
		t += s.charAt(Math.floor(Math.random()*26));
	}
	return t;
}

var sessionFields = [
    {name: 'session_id', type:'string'},
    {name: 'server', type:'string'},
    {name: 'token', type:'string'},
    {name: 'login', type:'string'},
    {name: 'save_pass', type:'boolean'},
    {name: 'agenda_id', type:'string'},
    {name: 'notes_id', type:'string'},
    {name: 'tasks_id', type:'string'},
    {name: 'images_id', type:'string'},
    {name: 'files_id', type:'string'},
    {name: 'bookmarks_id', type:'string'},
    {name: 'show_reminder', type:'boolean'},
    {name: 'show_reminder_before', type:'int'},
    {name: 'load_at_start', type:'boolean'},
    {name: 'update_interval', type:'int'},
    {name: 'next_days', type:'int'}
];

var sessionRecord = Ext.data.Record.create(sessionFields);

var SessionStore = Ext.extend(Ext.data.SimpleStore, {
	constructor: function(){
		SessionStore.superclass.constructor.call(this, {
			sortInfo: {
				field: 'server',
				direction: 'ASC'
			},
			fields: sessionFields
		});
	},
	
	file : 'beorganized.sessions',
	dataArray: [],
	
	addSession: function(aServer, aLogin, aToken, aNoteID, aLoadAtStart){
		var lID = Ext.uniqueId();
		var lRecord = new sessionRecord({
			session_id: lID,
			server: aServer,
			login: aLogin,
			save_pass: aToken?true:false,
			agenda_id: aNoteID,
			notes_id: aNoteID,
			tasks_id: aNoteID,
			images_id: aNoteID,
			files_id: aNoteID,
			bookmarks_id: aNoteID,
			show_reminder: true,
			show_reminder_before: 15,
			load_at_start: aLoadAtStart,
			update_interval: 30,
			next_days: 2,
			token: aToken?aToken:''
		});
		this.add(lRecord);
		this.save();
		return lID;
	},
	
	load : function(){
		var stateFile = air.File.applicationStorageDirectory.resolvePath(this.file);
		if(!stateFile.exists){
			this.dataArray = this.defaultData || [];
		}else{
			var stream = new air.FileStream();
			stream.open(stateFile, air.FileMode.READ);
			
			var stateData = stream.readObject();
			stream.close();
			
			this.dataArray = stateData || this.defaultData || [];					
		}
		this.removeAll();
		for(var i = 0; i<this.dataArray.length; i++){
			this.add(new Ext.data.Record(this.dataArray[i]));
		}
	},
	
	save : function(){
		var lData = this.dataArray = [];
		
		this.each(function(record){
			var lDataItem = {};
			for(var i = 0; i<sessionFields.length; i++){
				var lField = sessionFields[i];
				lDataItem[lField.name] = record.get(lField.name);
			}
//			air.trace(lDataItem.session_id+': '+lDataItem.save_pass);
			lData[lData.length] = lDataItem;
		});
		
        var stateFile = air.File.applicationStorageDirectory.resolvePath(this.file);
		var stream = new air.FileStream();
		stream.open(stateFile, air.FileMode.WRITE);
		stream.writeObject(lData);
		stream.close();
	}
	
});

var sessions = new SessionStore({});

sessions.load();
